<template>
  <div class="work-log-page">
    <!-- 月份选择器 -->
    <div class="month-selector">
      <el-button
        @click="changeMonth(-1)"
        :icon="ArrowLeft"
        circle
        size="small"
        class="month-btn"
      />
      <h2 class="month-title">{{ currentMonthText }}</h2>
      <el-button
        @click="changeMonth(1)"
        :icon="ArrowRight"
        circle
        size="small"
        class="month-btn"
      />
    </div>

    <!-- 日历视图 -->
    <div class="calendar-container">
      <!-- 星期标题 -->
      <div class="weekdays">
        <div class="weekday" v-for="day in weekdays" :key="day">{{ day }}</div>
      </div>

      <!-- 日期网格 -->
      <div class="calendar-grid">
        <div
          v-for="date in calendarDates"
          :key="date.key"
          class="calendar-cell"
          :class="{
            'other-month': !date.isCurrentMonth,
            'today': date.isToday,
            'has-logs': date.hasLogs,
            'selected': selectedDate === date.dateStr
          }"
          @click="selectDate(date)"
        >
          <div class="date-number">{{ date.day }}</div>
          <div class="log-indicator" v-if="date.hasLogs">
            <div class="log-dot"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 选中日期的工作日志 -->
    <div class="selected-date-logs" v-if="selectedDate">
      <div class="logs-header">
        <h3>{{ selectedDateText }} 工作记录</h3>
        <el-button
          type="primary"
          size="small"
          @click="showAddLogDialog = true"
          :icon="Plus"
        >
          添加记录
        </el-button>
      </div>

      <div class="logs-list" v-if="selectedDateLogs.length > 0">
        <div
          v-for="log in selectedDateLogs"
          :key="log.id"
          class="log-item"
        >
          <div class="log-content">
            <div class="client-info">
              <span class="client-name">{{ log.client.clientName }}</span>
              <span class="client-code">{{ log.client.clientCode }}</span>
            </div>
            <div class="service-info">
              <el-tag size="small" type="success">{{ log.service.serviceName }}</el-tag>
            </div>
            <div class="log-notes" v-if="log.notes">{{ log.notes }}</div>
          </div>
          <el-button
            type="danger"
            size="small"
            text
            @click="deleteLog(log)"
            :icon="Delete"
          />
        </div>
      </div>

      <div class="empty-logs" v-else>
        <el-empty description="当日暂无工作记录" :image-size="80" />
      </div>
    </div>

    <!-- 添加工作日志对话框 -->
    <el-dialog
      v-model="showAddLogDialog"
      title="添加工作记录"
      width="90%"
      :before-close="handleCloseAddDialog"
    >
      <el-form :model="addLogForm" label-position="top">
        <el-form-item label="选择服务项目">
          <el-select
            v-model="addLogForm.selectedServiceId"
            placeholder="请先选择服务项目"
            @change="onServiceChange"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="service in availableServices"
              :key="service.id"
              :label="service.serviceName"
              :value="service.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="选择客户" v-if="addLogForm.selectedServiceId">
          <el-input
            v-model="clientSearchKeyword"
            placeholder="输入客户代码或店名搜索"
            @input="searchClients"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <div class="client-search-results" v-if="searchResults.length > 0">
            <div
              v-for="client in searchResults"
              :key="client.id"
              class="client-option"
              :class="{ selected: addLogForm.clientId === client.id }"
              @click="selectClient(client)"
            >
              <div class="client-info">
                <span class="client-name">{{ client.clientName }}</span>
                <span class="client-code">{{ client.clientCode }}</span>
              </div>
              <div class="client-details">
                <el-tag size="small">{{ client.marketType }}</el-tag>
                <el-tag size="small" type="info">{{ client.terminalType }}</el-tag>
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="addLogForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入工作备注（可选）"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showAddLogDialog = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitAddLog"
          :loading="submitting"
          :disabled="!canSubmit"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, ArrowRight, Plus, Delete, Search } from '@element-plus/icons-vue'
import { trpc } from '@/utils/trpc'
import { AuthUtils } from '@/utils/auth'

// 响应式数据
const currentDate = ref(new Date())
const selectedDate = ref('')
const selectedDateLogs = ref([])
const showAddLogDialog = ref(false)
const submitting = ref(false)
const clientSearchKeyword = ref('')
const searchResults = ref([])
const availableServices = ref([])
// 月汇总：当月有日志的日期集合
const monthlyLogDates = ref<Set<string>>(new Set())


// 表单数据
const addLogForm = ref({
  selectedServiceId: null,
  clientId: null,
  notes: ''
})

// 日历相关数据
const weekdays = ['日', '一', '二', '三', '四', '五', '六']

// 计算属性
const currentMonthText = computed(() => {
  return `${currentDate.value.getFullYear()}年${currentDate.value.getMonth() + 1}月`
})

const selectedDateText = computed(() => {
  if (!selectedDate.value) return ''
  // 解析日期字符串，避免时区问题
  const [year, month, day] = selectedDate.value.split('-').map(Number)
  return `${month}月${day}日`
})

const canSubmit = computed(() => {
  return addLogForm.value.selectedServiceId && addLogForm.value.clientId
})

// 生成日历数据
const calendarDates = computed(() => {
  const year = currentDate.value.getFullYear()
  const month = currentDate.value.getMonth()

  // 获取当月第一天和最后一天
  const firstDay = new Date(year, month, 1)
  const lastDay = new Date(year, month + 1, 0)

  // 获取第一天是星期几
  const firstDayWeek = firstDay.getDay()

  const dates = []

  // 添加上个月的日期（填充）
  for (let i = firstDayWeek - 1; i >= 0; i--) {
    const date = new Date(year, month, -i)
    dates.push({
      key: `prev-${date.getDate()}`,
      day: date.getDate(),
      dateStr: formatDate(date),
      isCurrentMonth: false,
      isToday: false,
      hasLogs: false
    })
  }

  // 添加当月的日期
  for (let day = 1; day <= lastDay.getDate(); day++) {
    const date = new Date(year, month, day)
    const today = new Date()
    const dateStr = formatDate(date)
    const hasLogs = monthlyLogDates.value.has(dateStr)
    dates.push({
      key: `current-${day}`,
      day,
      dateStr,
      isCurrentMonth: true,
      isToday: isSameDay(date, today),
      hasLogs
    })
  }

  // 添加下个月的日期（填充到42个格子）
  const remainingCells = 42 - dates.length
  for (let day = 1; day <= remainingCells; day++) {
    const date = new Date(year, month + 1, day)
    dates.push({
      key: `next-${day}`,
      day,
      dateStr: formatDate(date),
      isCurrentMonth: false,
      isToday: false,
      hasLogs: false
    })
  }

  return dates
})

// 工具函数
const formatDate = (date: Date) => {
  // 使用本地时区的年月日，避免UTC转换问题
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const isSameDay = (date1: Date, date2: Date) => {
  return formatDate(date1) === formatDate(date2)
}

// 方法
const changeMonth = async (delta: number) => {
  const newDate = new Date(currentDate.value)
  newDate.setMonth(newDate.getMonth() + delta)
  currentDate.value = newDate
  selectedDate.value = ''
  selectedDateLogs.value = []
  await loadMonthlyLogSummary()
}

const selectDate = async (date: any) => {
  if (!date.isCurrentMonth) return

  selectedDate.value = date.dateStr
  await loadDateLogs(date.dateStr)
}

const loadDateLogs = async (dateStr: string) => {
  try {
    const managerId = getCurrentManagerId()
    if (!managerId) return

    const result = await trpc.workLog.byDate.query({
      managerId,
      // 按日固定时刻策略：一律 00:00:00.000Z
      date: `${dateStr}T00:00:00.000Z`
    })

    if (result.success) {
      selectedDateLogs.value = result.data
      if (result.data.length === 0) {
        // 空态提示（非打扰性）
        // ElMessage.info('当日暂无工作记录') // 可按需开启
      }
    }
  } catch (error) {
    console.error('加载日期工作日志失败:', error)
    ElMessage.error('加载当天工作记录失败')
  }
}

const loadMonthlyLogSummary = async () => {
  try {
    const managerId = getCurrentManagerId()
    if (!managerId) return

    // 计算当前月份起止
    const year = currentDate.value.getFullYear()
    const month = currentDate.value.getMonth()
    const monthStart = new Date(year, month, 1)
    const monthEnd = new Date(year, month + 1, 0)

    const result = await trpc.workLog.list.query({
      managerId,
      startDate: monthStart.toISOString(),
      endDate: new Date(monthEnd.getFullYear(), monthEnd.getMonth(), monthEnd.getDate(), 23, 59, 59, 999).toISOString(),
      page: 1,
      pageSize: 100,
    })

    const dateSet = new Set<string>()
    if (result.success) {
      const logs = result.data.data || result.data // 兼容不同数据包裹
      for (const log of logs) {
        const d = new Date(log.completionDate)
        const ds = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
        dateSet.add(ds)
      }
    }
    monthlyLogDates.value = dateSet
  } catch (error) {
    console.error('加载月度工作日志汇总失败:', error)
    ElMessage.error('加载当月日志汇总失败')
  }
}



const searchClients = async () => {
  if (!clientSearchKeyword.value.trim() || !addLogForm.value.selectedServiceId) {
    searchResults.value = []
    return
  }

  try {
    const managerId = getCurrentManagerId()
    if (!managerId) return

    const result = await trpc.workLog.searchClients.query({
      managerId,
      keyword: clientSearchKeyword.value.trim(),
      serviceId: addLogForm.value.selectedServiceId
    })

    if (result.success) {
      searchResults.value = result.data
    }
  } catch (error) {
    console.error('搜索客户失败:', error)
  }
}

const selectClient = async (client: any) => {
  addLogForm.value.clientId = client.id
  searchResults.value = []
  clientSearchKeyword.value = `${client.clientName} (${client.clientCode})`
}

const loadAvailableServices = async () => {
  try {
    const result = await trpc.service.list.query({ pageSize: 100 })
    if (result.success) {
      availableServices.value = result.data.data
    }
  } catch (error) {
    console.error('加载服务项目失败:', error)
  }
}

const onServiceChange = () => {
  // 清除客户选择
  addLogForm.value.clientId = null
  clientSearchKeyword.value = ''
  searchResults.value = []
}

const submitAddLog = async () => {
  if (!canSubmit.value) return

  submitting.value = true
  try {
    const managerId = getCurrentManagerId()
    if (!managerId) return

    // 为了避免重复记录检查，给记录添加时间戳使其唯一
    const completionDate = new Date(`${selectedDate.value}T00:00:00.000Z`)
    // 添加当前时间的时分秒，确保同一天可以有多条记录
    const now = new Date()
    completionDate.setHours(now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds())

    const result = await trpc.workLog.create.mutate({
      managerId,
      clientId: addLogForm.value.clientId,
      serviceId: addLogForm.value.selectedServiceId,
      completionDate: completionDate.toISOString(),
      notes: addLogForm.value.notes || undefined
    })

    if (result.success) {
      ElMessage.success('工作记录添加成功')
      showAddLogDialog.value = false
      await loadDateLogs(selectedDate.value)
    } else {
      ElMessage.error(result.message || '添加工作记录失败')
    }
  } catch (error) {
    console.error('添加工作记录失败:', error)
    ElMessage.error('添加工作记录失败')
  } finally {
    submitting.value = false
  }
  // 新增成功后，刷新本月汇总，以便日历小点同步
  await loadMonthlyLogSummary()
}

const deleteLog = async (log: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这条工作记录吗？', '确认删除', {
      type: 'warning'
    })

    await trpc.workLog.delete.mutate({
      id: log.id.toString(),
      managerId: getCurrentManagerId()
    })

    ElMessage.success('删除成功')
    await loadDateLogs(selectedDate.value)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除工作记录失败:', error)
      ElMessage.error('删除失败')
    }
  }
  // 删除成功或用户确认后，尝试刷新本月汇总（非阻塞）
  loadMonthlyLogSummary().catch(() => {})
}

const handleCloseAddDialog = () => {
  addLogForm.value = {
    selectedServiceId: null,
    clientId: null,
    notes: ''
  }
  clientSearchKeyword.value = ''
  searchResults.value = []
  showAddLogDialog.value = false
}

const getCurrentManagerId = () => {
  const user = AuthUtils.getUser<any>()
  // 后端返回 manager.id 为数字，这里读取 USER_INFO 中的 id
  return user?.id || null
}

// 生命周期
onMounted(async () => {
  try {
    // 默认选择今天
    const today = new Date()
    selectedDate.value = formatDate(today)
    await Promise.all([
      loadMonthlyLogSummary(),
      loadDateLogs(selectedDate.value),
      loadAvailableServices()
    ])
  } catch (error) {
    ElMessage.error('初始化工作日志数据失败，请稍后重试')
  }
})
</script>

<style scoped>
.work-log-page {
  padding: 0;
  background: #f5f7fa;
  min-height: 100vh;
}

.month-selector {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: white;
  border-bottom: 1px solid #ebeef5;
}

.month-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.month-btn {
  width: 32px;
  height: 32px;
}

.calendar-container {
  background: white;
  margin-bottom: 12px;
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  border-bottom: 1px solid #ebeef5;
}

.weekday {
  padding: 12px 0;
  text-align: center;
  font-size: 14px;
  font-weight: 500;
  color: #909399;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
}

.calendar-cell {
  aspect-ratio: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-right: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  position: relative;
  transition: background-color 0.2s;
}

.calendar-cell:hover {
  background: #f5f7fa;
}

.calendar-cell.other-month {
  color: #c0c4cc;
}

.calendar-cell.today {
  background: #e6f7ff;
  color: #1890ff;
  font-weight: 600;
}

.calendar-cell.selected {
  background: #409eff;
  color: white;
}

.calendar-cell.has-logs .log-indicator {
  position: absolute;
  bottom: 4px;
  right: 4px;
}

.log-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #67c23a;
}

.selected-date-logs {
  background: white;
  margin: 12px;
  border-radius: 8px;
  overflow: hidden;
}

.logs-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.logs-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.logs-list {
  padding: 0;
}

.log-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.log-item:last-child {
  border-bottom: none;
}

.log-content {
  flex: 1;
}

.client-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.client-name {
  font-weight: 500;
  font-size: 15px;
}

.client-code {
  font-size: 12px;
  color: #909399;
}

.service-info {
  margin-bottom: 4px;
}

.log-notes {
  font-size: 13px;
  color: #606266;
  margin-top: 4px;
}

.empty-logs {
  padding: 40px 20px;
}

.client-search-results {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-top: 8px;
}

.client-option {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.client-option:hover {
  background: #f5f7fa;
}

.client-option.selected {
  background: #e6f7ff;
}

.client-option:last-child {
  border-bottom: none;
}

.client-details {
  display: flex;
  gap: 8px;
  margin-top: 4px;
}

.service-options {
  max-height: 200px;
  overflow-y: auto;
}

.service-checkbox {
  display: block;
  margin-bottom: 8px;
}

:deep(.el-dialog) {
  margin-top: 5vh;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>
